import cv2

# print(cv2.data.haarcascades)  # 分类器的路径
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades+'haarcascade_profileface.xml')
img_path = 'd:/Pictures/Saved Pictures/timg (1).jpg'
# 夸张表情较难检测，测试timg (1).jpg
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(
    gray,   # 传入尽量使用灰度图加快检测
    scaleFactor = 1.02, # 滑动窗口放大倍数，约小会输出更多候选目标，但时间会越长
    minNeighbors = 1    # 至少拥有多少个矩形才定位目标，如果为0，则不做抑制，输出所有可能矩形，同一个face会有多个
)
print(len(faces))

for [x,y,w,h] in faces:
    # draw a retangle contained a face
    cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), thickness=2)

cv2.imwrite('a.png', img)   #save file
cv2.imshow('img', img)
key = cv2.waitKey(0)  #pause，ms，0则一直等待,press ESC to quit
if key == 27:   #esc=27
    cv2.destroyAllWindows()
